<template>
  <el-form :model="form" label-width="auto" style="max-width: 600px">
    <el-form-item label="类别名称">
      <el-input v-model="form.name" />
    </el-form-item>
    <el-form-item label="类别描述">
      <el-input v-model="form.description" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click.stop="onSubmit">确定</el-button>
      <el-button @click.stop="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { computed, onMounted, reactive, ref, watchEffect, shallowRef } from 'vue';
import { GetCategory,AddCategory,ChangeCategory } from '../../api/product.js';
import getDetailedDateTime from '../../untils/time.js'
import showMessage from '../../untils/elMessage.js';


// 可以绑定多个事件,但是必须只有一个emits
const emits = defineEmits(['close', 'confirm', 'closeChange', 'confirmChange'])  //注册事件，声明事件


const data = reactive({
  category: ''
})

const form = reactive({
  name: shallowRef(''),
  description: shallowRef(''),
  created: getDetailedDateTime(),
  category_id: shallowRef(''),
});

// 父组件传过来被选择项
const props = defineProps({
  change: Array
})
console.log(props.change);

console.log(!!props.change);

watchEffect(async () => {
  if (!!props.change) {
    form.name = props.change[0].category_name
    form.description = props.change[0].description
    form.category_id = props.change[0].category_id
  }
  else {
    form.name = '';
    form.description = '';
  }
  GetCategory().then(res => {
    data.category = res.data
  })
})


// 点击确认
const onSubmit = () => {
  if (!!props.change) {
    ChangeCategory({
      category_name: form.name,      
      description: form.description,
      category_id:form.category_id,
      updated_at: form.created,
    }).then(res => {
      showMessage(res)
      if (res.msgType == 8000) {
        emits('confirmChange', form)
      }
      
    })
  }
  else {
    AddCategory({
      category_name: form.name,
      description: form.description,
      created_at: form.created
    }).then(res => {
      showMessage(res)
      if (res.msgType == 8000) {
        emits('confirm')
      }
    })
  }
};


// 点击取消，重置输入框
const cancel = () => {
  form.name = '';
  form.description = '';
}
</script>